package cn.jietuo.second.class01;

import java.util.Arrays;
import java.util.Random;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/10/2
 * @description:  选择排序
 * 选择排序就是循环从所有的数据中找到最小的放到最前面来
 * 0~n-1  --> 0
 * 1~n-1  --> 1
 * 2~n-1  --> 2
 * ...
 * n-2~n-1 --> n-2
 * n-1
 */
public class Code01_SelectionSort {

    public static void selectionSort(int[] array){
        if (array == null || array.length < 2){
            return;
        }
        // 第一层循环控制次数
        for (int i = 0; i < array.length -1; i++) {
            // 第二层控制变量比较
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] > array[j]){
                    swap(i,j,array);
                }
            }
        }
    }

    private static void swap(int i, int j, int[] array) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    private static void printArray(int[] arr) {
        if (arr == null || arr.length < 1){
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println("");
    }

    public static void main(String[] args) {
//        int[] arr = {2,4,5,1,3,9,6};
//        printArray(arr);
//        selectionSort(arr);
//        printArray(arr);

        // 对数器
        Random random = new Random();
        // 次数
        int time = 50000;
        for (int i = 0; i < time; i++) {
            int arrayLength = random.nextInt(100) ;
            int[] randomArray = getRandomArray(arrayLength);
            int[] copyRandomArray = copyArray(randomArray);
            // 开始排序
            if (arrayLength == 0){
               continue;
            }
            selectionSort(randomArray);
            Arrays.sort(copyRandomArray);

            for (int j = 0; j < arrayLength; j++) {
                if (randomArray[j] != copyRandomArray[j]){
                    System.out.println("fucking------");
                    System.out.println("randomArray:");
                    printArray(randomArray);
                    System.out.println("copyRandomArray");
                    printArray(copyRandomArray);
                }
            }
        }
        System.out.println("Nice------");
    }

    private static int[] copyArray(int[] randomArray) {
        if (randomArray == null || randomArray.length < 1){
            return null;
        }
        int[] copy = new int[randomArray.length];
        for (int i = 0; i < randomArray.length; i++) {
            copy[i] = randomArray[i];
        }
        return copy;
    }

    private static int[] getRandomArray(int arrayLength) {
        Random random = new Random();
        int[] randomArray = new int[arrayLength];
        for (int i = 0; i < arrayLength; i++) {
            randomArray[i] = random.nextInt(100)  ;
        }
        return randomArray;
    }

}
